//
//  SISSTenantEnrollViewController.m
//  SISSAPP
//
//  Created by 袁应荣 on 2017/12/18.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSTenantEnrollViewController.h"
#import "SISSEnrollTenantViewModel.h"
#import "SISSEnrollTenantDetailViewController.h"
#import "SISSJsonRequestNetworkingManager+Registration.h"
#import "SISSMyEnrollTenantViewController.h"
#import "SISSTenantRegistSuccessViewController.h"

@interface SISSTenantEnrollViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (strong, nonatomic) SISSEnrollTenantViewModel *enrollTenantViewModel;
/* tableView */
@property (weak, nonatomic) SISSBaseTableView *tableView;
/* 下一步按钮 */
@property (weak, nonatomic) UIButton *nextStepButton;

/** 记录是否点击了确定 */
@property (assign, nonatomic) BOOL isConfirm;

@end

@implementation SISSTenantEnrollViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"租客登记";
    
    // 添加左侧的关闭按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    
    if (self.isChange) {
        [self.enrollTenantViewModel assignmentWithTenantModel:self.tenantModel];
        [self.nextStepButton setTitle:@"保存" forState:UIControlStateNormal];
    }
}

/**
 返回关闭按钮的点击事件
 */
- (void)back {
    
    [self.view endEditing:YES];
    
    if (self.isConfirm) { // 判断是否点击了确定
        [self dismissViewControllerAnimated:YES completion:nil];
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        NSString *title = @"放弃";
        NSString *message = self.isChange ? @"修改还未完成，您确定放弃吗？" : @"登记还未完成，您确定放弃吗？";
        [self alertConfirmCacellActionAlertWithTitle:title message:message];
    }
}

#pragma mark - 代理
#pragma mark -- UITableViewDelegate & UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.enrollTenantViewModel getSectionCount];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.enrollTenantViewModel getRowsInSection:section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //    NSArray *arr = self.dataArr[indexPath.section];
    UITableViewCell *cell = [self.enrollTenantViewModel getCell:tableView indexPath:indexPath];
    if (self.isChange && indexPath.section == 3) {
        cell.userInteractionEnabled = NO;
    }
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}



- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return [self.enrollTenantViewModel getHeightForHeaderInSection:section];
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    return [self.enrollTenantViewModel getViewHeaderInSection:section];
}

// 取消tableView组头悬停
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat sectionHeaderHeight = 40;
    if (scrollView.contentOffset.y <= sectionHeaderHeight&&scrollView.contentOffset.y >= 0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y >= sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}

/**
 必选提示
 
 @return 返回YES时需要填写或选择
 */
- (BOOL)requiredTip {
    
    [self.view endEditing:YES];
    
    NSString *ID = self.tenantModel.ID;
    self.tenantModel = [self.enrollTenantViewModel dataArrayToTenantModel];
    self.tenantModel.ID = ID;
    
    if (!self.tenantModel.region || self.tenantModel.region.length == 0) {
        [SISSTools showSVErrorTitle:@"请选择区域" andTime:2 andColor:YES];
        return YES;
    }
  
    if (!self.tenantModel.minPrice || self.tenantModel.minPrice.length == 0) {
        [SISSTools showSVErrorTitle:@"请输入最低预算" andTime:2 andColor:YES];
        return YES;
    }
    if (!self.tenantModel.maxPrice || self.tenantModel.maxPrice.length == 0) {
        [SISSTools showSVErrorTitle:@"请输入最高预算" andTime:2 andColor:YES];
        return YES;
    }
    if (!self.tenantModel.houseType || self.tenantModel.houseType.length == 0) {
        [SISSTools showSVErrorTitle:@"请选择户型" andTime:2 andColor:YES];
        return YES;
    }
    if (!self.tenantModel.residents || self.tenantModel.residents.length == 0) {
        [SISSTools showSVErrorTitle:@"请选择居住人数" andTime:2 andColor:YES];
        return YES;
    }
    if (!self.tenantModel.checkinTime || self.tenantModel.checkinTime.length == 0) {
        [SISSTools showSVErrorTitle:@"请选择入住时间" andTime:2 andColor:YES];
        return YES;
    }
    if (!self.tenantModel.renterName || self.tenantModel.renterName.length == 0) {
        [SISSTools showSVErrorTitle:@"请输入租客姓名" andTime:2 andColor:YES];
        return YES;
    }
    if (!self.tenantModel.idNumber || self.tenantModel.idNumber.length == 0) {
        [SISSTools showSVErrorTitle:@"请输入租客身份证号码" andTime:2 andColor:YES];
        return YES;
    }
    if (![NSString accurateVerifyIDCardNumber:self.tenantModel.idNumber]) {
        [SISSTools showSVErrorTitle:@"您输入的身份证号码格式不正确" andTime:2 andColor:YES];
        return YES;
    }
    if (!self.tenantModel.mobile || self.tenantModel.mobile.length == 0) {
        [SISSTools showSVErrorTitle:@"请输入租客手机号码" andTime:2 andColor:YES];
        return YES;
    }
    if (![NSString checkTelNumber:self.tenantModel.mobile]) {
        [SISSTools showSVErrorTitle:@"您输入的手机号码格式不正确" andTime:2 andColor:YES];
        return YES;
    }
    if ([self.tenantModel.minPrice floatValue] > [self.tenantModel.maxPrice floatValue]) {
        [SISSTools showSVErrorTitle:@"最高预算不能小于最低预算字" andTime:2 andColor:YES];
        return YES;
    }
    return NO;
}


#pragma mark - 按钮点击事件
#pragma mark -- 下一步按钮点击事件
- (void)nextStepButtonClickAction {
    
    if ([self requiredTip]) return;

    if (!self.isChange) {
        [self enrollTenant];
    } else { 
        [self updateTenant];
    }
}

- (void)enrollTenant {
    
    [kJsonRequestNetworkingManager insertTenantResourceOfflineWithTenantModel:self.tenantModel successBlock:^(id responseObject) {
        
        if ([responseObject[@"code"] integerValue] == 200) { // 登记成功
            [SISSTools showSVTitle:@"登记成功！" andTime:1.0 andColor:YES];
            self.isConfirm = YES;
            if (self.isRegistration) {
                
//                SISSEnrollTenantDetailViewController *vc = [[SISSEnrollTenantDetailViewController alloc] init];
//                vc.tenantModel = self.tenantModel;
//                vc.isRegistration = self.isRegistration;
                
                SISSTenantRegistSuccessViewController *vc = [[SISSTenantRegistSuccessViewController alloc] init];
                vc.isRegistration = self.isRegistration;
                vc.arrId = responseObject[@"data"];
                [self.navigationController pushViewController:vc animated:YES];
                
            } else {
                
                [self.navigationController popViewControllerAnimated:YES];
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        } else { // 登记失败
            
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                [SISSTools showSVTitle:responseObject[@"message"] andTime:1.0 andColor:YES];
            }];
        }
        
    } failed:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

- (void)updateTenant {
    [kJsonRequestNetworkingManager updateTenantResourceWithTenantModel:self.tenantModel successBlock:^(id responseObject) {
        
        if ([responseObject[@"code"] integerValue] == 200) { // 修改成功
            
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                
                [SISSTools showSVTitle:@"修改成功！" andTime:1.0 andColor:YES];
            }];
            
            for (UIViewController *controller in self.navigationController.viewControllers) {
                if ([controller isKindOfClass:[SISSMyEnrollTenantViewController class]]) {
                    [self.navigationController popToViewController:controller animated:YES];
                }
            }
        }
        
    } failed:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

#pragma mark - UI
- (void)setupSubviews {
    [super setupSubviews];
    
    self.enrollTenantViewModel = [[SISSEnrollTenantViewModel alloc] init];
    
    SISSBaseTableView *tableView = [[SISSBaseTableView alloc] init];
    tableView.estimatedRowHeight = 44;
    tableView.rowHeight = UITableViewAutomaticDimension;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.enrollTenantViewModel registContractClass:tableView];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    self.enrollTenantViewModel.tableView = tableView;
    
    UIView *footerView = [[UIView alloc ] initWithFrame:CGRectMake(0, 0, [SISSPublicSingleton shared].screenWidth, 66)];
    
    UIButton *nextStepButton = [UIButton buttonWithType:UIButtonTypeCustom];
    nextStepButton.layer.cornerRadius = 10;
    nextStepButton.layer.masksToBounds = YES;
    [nextStepButton setTitle:@"下一步" forState:UIControlStateNormal];
    [nextStepButton setBackgroundColor:MAIN_COLOR];
    [nextStepButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [nextStepButton addTarget:self action:@selector(nextStepButtonClickAction) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:nextStepButton];
    self.nextStepButton = nextStepButton;
    
    [self.nextStepButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(footerView).offset(16);
        make.right.equalTo(footerView).offset(-16);
        make.bottom.equalTo(footerView).offset(-8);
        make.height.mas_equalTo(44);
    }];
    
    self.tableView.tableFooterView = footerView;
}

#pragma mark - 约束
- (void)initConstraint {
    [super initConstraint];
    
    WeakSelf
    //    CGFloat viewHeight = 44.0;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(weakSelf.view);
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(weakSelf.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.equalTo(weakSelf.view);
        }
    }];
}

@end
